package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.StatementType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        // 对不同类型的SQL标签进行解析
        Arrays.stream(StatementType.values()).map(StatementType::getCode)
                .forEach(code -> {
                    List<Element> list = rootElement.selectNodes("//" + code);
                    if (null != list && !list.isEmpty()) {
                        resolveSqlSegment(namespace, list);
                    }
                });
    }

    private void resolveSqlSegment(String namespace, List<Element> list) {
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            String statementTypeStr = element.getName();
            StatementType statementType = StatementType.getInstance(statementTypeStr);
            if (null == statementType) {
                throw new IllegalArgumentException(String.format("error statement type: %s", statementTypeStr));
            }

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setStatementType(statementType);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
